{% extends "base.html" %}

{% block title %}学生成绩查询系统{% endblock %}

{% block content %}
<a href="/admin" class="admin-link">管理后台</a>

<div class="container">
    <div class="header">
        <h1>🎓 学生成绩查询</h1>
        <p>请选择查询方式：按学生姓名查询成绩或按班级查询学生名单</p>
    </div>
    
    <div class="alert"></div>
    
    <!-- 查询方式选择 -->
    <div class="query-tabs">
        <button type="button" class="tab-btn active" onclick="switchTab('student')">👤 按姓名查询</button>
        <button type="button" class="tab-btn" onclick="switchTab('class')">🏫 按班级查询</button>
    </div>
    
    <!-- 学生姓名查询表单 -->
    <form id="searchForm" class="query-form active">
        <div class="form-group">
            <label for="studentName">学生姓名</label>
            <input type="text" id="studentName" name="studentName" placeholder="请输入学生姓名" required>
        </div>
        
        <button type="submit" class="btn">🔍 查询成绩</button>
    </form>
    
    <!-- 班级查询表单 -->
    <form id="classForm" class="query-form">
        <div class="form-group">
            <label for="className">班级名称</label>
            <input type="text" id="className" name="className" placeholder="请输入班级名称（如：1班、2025级1班）" required>
        </div>
        
        <button type="submit" class="btn">🏫 查询班级学生</button>
    </form>
    
    <div id="results"></div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 切换查询方式
    function switchTab(type) {
        // 更新选项卡状态
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        document.querySelectorAll('.query-form').forEach(form => form.classList.remove('active'));
        
        if (type === 'student') {
            document.querySelector('.tab-btn[onclick="switchTab(\'student\')"]').classList.add('active');
            document.getElementById('searchForm').classList.add('active');
        } else {
            document.querySelector('.tab-btn[onclick="switchTab(\'class\')"]').classList.add('active');
            document.getElementById('classForm').classList.add('active');
        }
        
        // 清空结果
        document.getElementById('results').innerHTML = '';
        hideAlert();
    }

    // 学生姓名查询
    document.getElementById('searchForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const studentName = document.getElementById('studentName').value.trim();
        if (!studentName) {
            showAlert('请输入学生姓名', 'error');
            return;
        }
        
        fetch('/api/search_student', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                student_name: studentName
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 处理返回的学生数据（可能有多个同名学生）
                if (data.data && data.data.length > 0) {
                    displayStudentResult(data.data[0]); // 显示第一个匹配的学生
                } else {
                    showAlert('未找到学生信息', 'error');
                    document.getElementById('results').innerHTML = '';
                }
            } else {
                showAlert(data.message || '查询失败', 'error');
                document.getElementById('results').innerHTML = '';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('网络错误，请稍后重试', 'error');
        });
    });
    
    // 班级查询
     document.getElementById('classForm').addEventListener('submit', function(e) {
         e.preventDefault();
         
         const className = document.getElementById('className').value.trim();
         if (!className) {
             showAlert('请输入班级名称', 'error');
             return;
         }
         
         fetch(`/api/get_class_students/${encodeURIComponent(className)}`, {
             method: 'GET'
         })
         .then(response => response.json())
         .then(data => {
             if (data.success) {
                 // 提取学生姓名列表
                 const studentNames = data.students.map(student => student.student_name);
                 displayClassStudents(studentNames, className);
             } else {
                 showAlert(data.message || '查询失败', 'error');
                 document.getElementById('results').innerHTML = '';
             }
         })
         .catch(error => {
             console.error('Error:', error);
             showAlert('网络错误，请稍后重试', 'error');
         });
     });
    
    // 显示学生成绩结果
     function displayStudentResult(student) {
         const resultsDiv = document.getElementById('results');
         
         let html = `
             <div class="result-card">
                 <h3>📊 查询结果</h3>
                 <div class="student-info">
                     <p><strong>姓名：</strong>${student.student_name}</p>
                     <p><strong>班级：</strong>${student.class_name}</p>
         `;
         
         // 显示各科成绩
         if (student.subject_data) {
             for (const [subject, score] of Object.entries(student.subject_data)) {
                 if (score !== undefined && score !== null && score !== '') {
                     html += `<p><strong>${subject}：</strong>${score}</p>`;
                 }
             }
         }
         
         html += `
                 </div>
             </div>
         `;
         
         resultsDiv.innerHTML = html;
         hideAlert();
     }
    
    // 显示班级学生列表
    function displayClassStudents(students, className) {
        const resultsDiv = document.getElementById('results');
        
        if (students.length === 0) {
            showAlert(`未找到班级"${className}"的学生信息`, 'error');
            resultsDiv.innerHTML = '';
            return;
        }
        
        let html = `
            <div class="student-list">
                <h3>🏫 ${className} - 学生名单 (共${students.length}人)</h3>
                <div class="student-grid">
        `;
        
        students.forEach(student => {
            html += `
                <div class="student-item" onclick="queryStudentByName('${student}')">
                    <div class="name">${student}</div>
                </div>
            `;
        });
        
        html += `
                </div>
                <p style="margin-top: 15px; color: #666; font-size: 14px;">💡 点击学生姓名可查看详细成绩</p>
            </div>
        `;
        
        resultsDiv.innerHTML = html;
        hideAlert();
    }
    
    // 点击学生姓名查询成绩
    function queryStudentByName(name) {
        // 切换到学生查询模式
        switchTab('student');
        
        // 填入学生姓名
        document.getElementById('studentName').value = name;
        
        // 自动提交查询
        document.getElementById('searchForm').dispatchEvent(new Event('submit'));
    }
    
    function showAlert(message, type = 'info') {
        const alertDiv = document.querySelector('.alert');
        alertDiv.textContent = message;
        alertDiv.className = `alert ${type}`;
        alertDiv.style.display = 'block';
    }
    
    function hideAlert() {
        const alertDiv = document.querySelector('.alert');
        alertDiv.style.display = 'none';
    }
</script>
{% endblock %}